#coding:utf-8
import os,sys,time
from bs4 import BeautifulSoup
reload(sys)
sys.setdefaultencoding('utf-8')

class GetData(object):
	"""docstring for Dict"""
	def __init__(self,tdd='Compared'):
		self.Chrome = 'Chrome63_Ditnotpass'
		self.testdatadir = tdd
		self.DICTIONARY = {
			'Version':self.version(0),
			'All':self.all_data(0),                                                                                                                                                                                                                                                                                                                                                                                                                                                                       
			'Pass':self.pass_data(0),

			'Crash':self.get_SortData(0,'Crash.txt'),
			'Crashdata':self.get_SortData(1,'Crash.txt'),
			'Image_Failure':self.get_SortData(0,'Image_Failure.txt'),
			'Image_Failuredata':self.get_SortData(1,'Image_Failure.txt'),
			'Image_Text_Failure':self.get_SortData(0,'Image_Text_Failure.txt'),
			'Image_Text_Failuredata':self.get_SortData(1,'Image_Text_Failure.txt'),
			'Missing':self.get_SortData(0,'Missing.txt'),
			'Missingdata':self.get_SortData(1,'Missing.txt'),
			'Skipped':self.get_SortData(0,'Skipped.txt'),
			'Text_Failure':self.get_SortData(0,'Text_Failure.txt'),
			'Text_Failuredata':self.get_SortData(1,'Text_Failure.txt'),
			'Timeout':self.get_SortData(0,'Timeout.txt'),
			'Timeoutdata':self.get_SortData(1,'Timeout.txt'),
			'Skippeddata':self.get_SortData(1,'Skipped.txt'),

			'stablefail':self.get_stablefail(),
			'floatfail':self.get_floatfail(0),
			'floatdata':self.get_floatfail(1),
			'Add':self.get_add(0),
			'Add_data':self.get_add(1),
		};

	def version(self,key=0):
		return 'Hwbrowser'

	def all_data(self,key=0):
		return 47983


	def pass_data(self,key=0):
		return 47983

	def get_stablefail(self,stablecount=0):
		try:
			fns = [os.path.join(root, fn) for root, dirs, files in os.walk(os.path.join(os.getcwd(),self.Chrome)) for fn in files if '.txt' in fn and not 'stablefail' in fn and not 'floatfail' in fn]
			for f in fns:
				with open(f) as fn:
					items = [x.split() for x in fn.readlines()][0]
					stablecount += len(items)
			return stablecount
		except Exception, e:
			print e
			return None
		

	def get_floatfail(self,key=0):
		try:
			with open(os.path.join(os.getcwd(),self.Chrome,'floatfail.txt')) as fn:
				items = [x.split() for x in fn.readlines()][0]
			if key==1:
				return items
			return len(items)
		except Exception as e:
			if key==1:
				return []
			return 0

	def get_add(self,key=0):
		if self.testdatadir == 'Compared':
			try:
				N = [os.path.join(root, fn) for root, dirs, files in os.walk(os.path.join(os.getcwd(),self.testdatadir)) for fn in files if '.txt' in fn]
				with open(os.path.join(os.getcwd(),self.testdatadir,'addfailure.txt'),'wb') as af:
					for i in N:
						if os.path.getsize(i)==0:
							continue
						with open(i) as f:
							items = [x.split() for x in f.readlines()][0]
							for x in items:
								af.writelines(x+'\r')

				with open(os.path.join(os.getcwd(),self.testdatadir,'addfailure.txt')) as ad:
					s = [x.split() for x in ad.readlines()][0]
				if key==0:
					return len(s)
				return s
			except Exception, e:
				raise ('如果提示这行报错，试着再执行一下？')
			finally:
				try:
					self.Contrast_processing()
				except Exception, e:
					raise e
		else:
			pass
				

	def get_SortData(self, key=0, sort=''):
		try:
			if not sort in os.listdir(os.path.join(os.getcwd(),self.testdatadir)):
				self.html_process_txt(sort[:-4])
			while True:
				with open(os.path.join(os.getcwd(),self.testdatadir,sort)) as fn:
					try:
						items = [x.split() for x in fn.readlines()][0]
					except Exception, e:
						items = []
				if key==1:
					return items
				return len(items)
		except Exception, e:
			raise e

	def html_process_txt(self,name=''):
		l1 = []
		fns = [os.path.join(root, fn) for root, dirs, files in os.walk(os.path.join(os.getcwd(),self.testdatadir,name)) for fn in files if '.html' in fn]
		try:
			for fn in fns:
				soup = BeautifulSoup(open(fn),'html.parser')
				for title in soup.select('a'):
					l1.append(title.get('href'))
			
			#删除出现一次的用例
			#只有在获取稳定失败的用例，对比多次失败结果时使用下面的方法
			# l1 = [i for i in l1 if l1.count(i) != 1]

			#删除重复的用例,顺序保持不变
			l2 = sorted(set(l1),key=l1.index)
			hf = open(os.path.join(os.getcwd(),self.testdatadir,name+'.txt'),'wb')
			for i in l2:
				hf.write(i+'\r')
			hf.close()
		except Exception, e:
			raise e

	def Contrast_processing(self,Chrome='Chrome63_Ditnotpass',HW='HuaWei_Didnotpass',new='Compared'):
		try:
			C = [os.path.join(root, fn) for root, dirs, files in os.walk(os.path.join(os.getcwd(),Chrome)) for fn in files if '.txt' in fn and not 'stablefail' in fn and not 'floatfail' in fn]
			H = [os.path.join(root, fn) for root, dirs, files in os.walk(os.path.join(os.getcwd(),HW)) for fn in files if '.txt' in fn and not 'floatfail' in fn]

			filename = [x.split('\\')[-1] for x in H]
			for i in range(len(H)):
				with open(str(H[i])) as h:
					s1 = set([y.split('/')[-1] for y in [x.split() for x in h.readlines()][0]])
				with open(str(C[i])) as c:
					s2 = set([y.split('/')[-1] for y in [x.split() for x in c.readlines()][0]])
				s = list(s1.difference(s2))

				if len(s)==0:
					open(os.path.join(os.getcwd(),new,filename[i]),'wb')
				else:
					with open(os.path.join(os.getcwd(),new,filename[i]),'wb') as n:
						with open(str(H[i])) as h:
							ls = [x.split() for x in h.readlines()][0]
							for a in s:
								for b in ls:
									if b.count(a):
										n.write(b+'\r')
									else:
										pass
							n.close()
		except Exception as e:
			print e

def Handle():
	'''
		HuaWei_Didnotpass、Compared 都是文件夹名称，存在在同级目录下。
		HuaWei_Didnotpass 存放的是版本对应的layouttest测试报告，html文件
		此方法传参调用GetData类，先处理华为生成的报告，然后与Chrome63报告进行对比，结果保存在Compared文件夹下
	'''
	tdd = ['HuaWei_Didnotpass','Compared']
	try:
		for i in tdd:
			GetData(i)
	except Exception, e:#这一步报错之后再执行 GetData('Compared')
		if 'not str' in str(e):
			GetData('Compared')
		else:
			raise e

if __name__ == '__main__':
	GetData()